package com.liuc.practice.bank.transfer.utils;

import com.liuc.practice.bank.transfer.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author Liu Chang
 * @Date 2021/2/23 11:26 上午
 */
@Service
public class ConnectionUtils {

    // 存储当前线程中的连接（因为事务是连接的是事务，所以存储连接即可）
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    public Connection getConnectionFromCurrentThread() {
        Connection connection = threadLocal.get();

        if (connection == null) {
            try {
                threadLocal.set(DruidUtils.getInstance().getConnection());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return threadLocal.get();
    }
}
